<template>
 <div>
  <el-upload
  class="upload-demo"
  ref="upload"
  action="#"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  :on-success="handleUploadSuccess"
  :on-progress="uploadFileProcess"
  :http-request="handleUpload"
  :multiple="true"
  :limit="10"
  :on-exceed="handleExceed"
  :headers="headers"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过200Mb</div>
</el-upload>



 </div>
</template>
<script>
import { getToken } from "@/utils/auth";

import { put, signatureUrl, getFileNameUUID } from '@/utils/tool'
import { constantRoutes } from "../../router";
  export default {
    props: {
    // 值
    value: [String, Object, Array]
    },
    data() {
      return {
        fileList: [],
        ffList:[],
        ossUrl: process.env.VUE_APP_OSSURL,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload/oss", // 上传的图片服务器地址
        headers: {
        Authorization: "Bearer " + getToken(),
      },
      };
    },
    watch: {
      value: {
        handler(val) {
          if (val) {
            let temp = 1;
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.fileList = list.map(item => {
              if (typeof item === "string") {
                item = { name: this.getFileName(item), url: item };
              }
              item.uid = item.uid || new Date().getTime() + temp++;
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
  },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {

         return this.$confirm(`确定移除 ${ file.name }？`)
      },
      uploadFileProcess(event, file, fileList) {
        this.fileList = fileList;
        for (let i = 0; i < this.fileList.length; i++) {
          if(file.name === this.fileList[i].name){
            this.fileList[i].progressFlag = true;
            this.fileList[i].successFlag = false;
            if(event.percent != 100){
              this.fileList[i].progressPercent = event.percent;
            }
            break;
          }
        }
      },

      handleUpload(option) {
        // 获取文件的后缀名
        // let objName = getFileNameUUID()
        var obj = option.file.name
        var index = obj.lastIndexOf(".");
        obj = obj.substring(index,obj.length);
        // 生成的文件名，保留文件后缀名，进行拼接
        let objName = getFileNameUUID() + this.getFileName(option.file.name) + obj
        // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
        var pp = `video/xs/${objName}`;
        var uid =  option.file.uid;
        put(pp, option.file).then(res => {
          this.ffList.push({name: objName , url:pp});
          setTimeout(()=>{
            this.$emit("input", this.listToString(this.ffList));
          })
          option.onSuccess()
        })
      },

    handleUploadSuccess(res, file,fileList) {
     //  console.log("11111111111");
     //  if(fileList.every(it => it.status == 'success')) {
     //  fileList.map(item => {
     //    console.log(item);
     //    //只push新上传的 （带有response）
     //    item.response && this.fileList.push({name: this.getFileName(item.response.fileName) ,url:item.response.fileName});
     //  })
     //  setTimeout(()=>{
     //    this.$emit("input", this.listToString(this.fileList));
     //   })
     // }

      // // this.$message.success("上传成功");
      // console.log(res)
      // this.fileList.push({ name: this.getFileName(res.fileName), url: res.fileName });
      // console.log(this.fileList);
    },
      // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
    }
  }
</script>
<style lang="scss" scoped>
::v-deep .el-upload-list__item {
   transition: none !important;
 }
</style>
